define([ 'util/JQuery', 'util/Knockout', 'domain/AvailableGame', 'domain/Achievement', 'util/ArrayUtil', 'util/Timer', 'util/Initializer' ], function($, ko, AvailableGame, Achievement, arrayUtil, Timer, Initializer) {

	var model = function(initUI) {
		var self = this;

		// attributes
		self.gameId = ko.observable();

		self.initUI = initUI;

		self.games = ko.observableArray([]);

		self.gameName = ko.observable();

		self.runningGame = ko.observable(false);
		
		self.throttledGameNameValue = ko.computed(self.gameName).extend({
			throttle : 400
		});

		self.throttledGameNameValue.subscribe(function(val) {			
			stopGameFetchinState();
			self.gameNameFilterValue = val;
			startGameFetchinState();
		}, self);
		
		self.gameNameFilterValue = "";
		
		var gamesLoadTimer = new Timer();

		//
		var initializer = new Initializer("Game list");

		self.createGame = function() {
			$.put("game").success(startGame);
		};

		self.joinGame = function(game) {
			$.post("game/{0}".format(game.id)).success(startGame);
		};

		self.continueGame = function() {
			window.location = "game/{0}".format(self.gameId());
		};

		startGame = function(gameId) {
			window.location = "game/{0}".format(gameId);
		};

		gameLoad = function() {
			var gameFetchUrl = "games";
			
			if (self.gameNameFilterValue !== '') {
				gameFetchUrl += "?gameOwnerFilter={0}".format(self.gameNameFilterValue);
			};
			
			$.get(gameFetchUrl).success(setAvailableGame);
		};
		
		var setAvailableGame = function(games, a, jqXHR) {
			
			console.log('succes', jqXHR);
			
			self.gameId(games.gameId);
			self.runningGame(games.gameId != null);
			
			var newGames = $.map(games.availableGame, function(item) {
				return new AvailableGame(item);
			});
			
			arrayUtil.arrayExecuteChanges(self.games, newGames);
		
			initializer.init(initUI);

		};
		
		var startGameFetchinState = function() {
			gameLoad();
			gamesLoadTimer.start(gameLoad, 3000);
		};

		var stopGameFetchinState = function() {
			gamesLoadTimer.stop();
		};

		// fist load
		startGameFetchinState();

	};

	return model;
});
